package com.han.jdbc.mybatis._01;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Test;



/**
* @author hanpeng
* @version 创建时间：2020年7月17日 下午8:16:25
* @ClassName 类名称
* @Description 类描述
*/
public class SqlSessionFactoryTest {
	public static void main(String[] args) {
	}
	@Test
	public void getSqlSessionFactoryFromXml() {
		String resource="01mybatis-config.xml";
		SqlSession sqlSession=null;
		try {
			InputStream is = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
			sqlSession = sqlSessionFactory.openSession();
			Object object=sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", new Integer(1));
			System.out.println(object);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(sqlSession!=null) {
					sqlSession.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	@Test
	public void getSqlSessionFactoryFromJavaCode() {
		PooledDataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver", 
				"jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&useAffectedRows=true&characterEncoding=utf-8&useSSL=false", 
				"root",
				"123456");
		
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
		configuration.addMapper(BlogMapper.class);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
		String name = mapper.selectBlog(1);
		System.out.println(name);
		sqlSession.close();
		
	}
}
